import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'email_list_page.dart';
import 'email_service.dart';

class EmailLoginPage extends StatefulWidget {
  const EmailLoginPage({super.key});

  @override
  State<EmailLoginPage> createState() => _EmailLoginPageState();
}

class _EmailLoginPageState extends State<EmailLoginPage> {
  final _formKey = GlobalKey<FormState>();
  
  final _emailController = TextEditingController();
  final _passwordController = TextEditingController();
  final _popServerController = TextEditingController();
  final _popPortController = TextEditingController(text: '995');
  
  bool _isSecure = true;
  bool _isLoading = false;
  bool _rememberMe = true;
  String? _errorMessage;

  @override
  void initState() {
    super.initState();
    _loadSavedCredentials();
  }

  @override
  void dispose() {
    _emailController.dispose();
    _passwordController.dispose();
    _popServerController.dispose();
    _popPortController.dispose();
    super.dispose();
  }

  Future<void> _loadSavedCredentials() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      _emailController.text = prefs.getString('email') ?? '';
      _passwordController.text = prefs.getString('password') ?? '';
      _popServerController.text = prefs.getString('popServer') ?? '';
      _popPortController.text = prefs.getString('popPort') ?? '995';
      _isSecure = prefs.getBool('isSecure') ?? true;
    });
  }

  Future<void> _saveCredentials() async {
    if (!_rememberMe) return;
    
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString('email', _emailController.text);
    await prefs.setString('password', _passwordController.text);
    await prefs.setString('popServer', _popServerController.text);
    await prefs.setString('popPort', _popPortController.text);
    await prefs.setBool('isSecure', _isSecure);
  }

  Future<void> _login() async {
    if (!_formKey.currentState!.validate()) return;

    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });

    try {
      // 保存凭据
      await _saveCredentials();
      
      // 设置邮箱服务配置
      EmailService.setConfig(
        username: _emailController.text,
        password: _passwordController.text,
        popServer: _popServerController.text,
        popPort: int.parse(_popPortController.text),
        isPopSecure: _isSecure,
      );
      
      // 测试连接
      await EmailService.testConnection();
      
      if (!mounted) return;
      
      // 导航到邮件列表页面
      Navigator.of(context).pushReplacement(
        MaterialPageRoute(builder: (context) => const EmailListPage()),
      );
    } catch (e) {
      setState(() {
        _errorMessage = '连接失败: $e';
      });
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('邮箱登录'),
        backgroundColor: Theme.of(context).colorScheme.primary,
        foregroundColor: Theme.of(context).colorScheme.onPrimary,
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                const SizedBox(height: 20),
                const Icon(
                  Icons.email,
                  size: 80,
                  color: Colors.blue,
                ),
                const SizedBox(height: 20),
                const Text(
                  '请输入您的邮箱信息',
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                  textAlign: TextAlign.center,
                ),
                const SizedBox(height: 20),
                
                // 邮箱地址
                TextFormField(
                  controller: _emailController,
                  decoration: const InputDecoration(
                    labelText: '邮箱地址',
                    hintText: 'example@example.com',
                    prefixIcon: Icon(Icons.email),
                    border: OutlineInputBorder(),
                  ),
                  keyboardType: TextInputType.emailAddress,
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return '请输入邮箱地址';
                    }
                    return null;
                  },
                ),
                const SizedBox(height: 16),
                
                // 密码
                TextFormField(
                  controller: _passwordController,
                  decoration: InputDecoration(
                    labelText: '密码',
                    prefixIcon: const Icon(Icons.lock),
                    border: const OutlineInputBorder(),
                    suffixIcon: IconButton(
                      icon: Icon(
                        _isSecure ? Icons.visibility_off : Icons.visibility,
                      ),
                      onPressed: () {
                        setState(() {
                          _isSecure = !_isSecure;
                        });
                      },
                    ),
                  ),
                  obscureText: _isSecure,
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return '请输入密码';
                    }
                    return null;
                  },
                ),
                const SizedBox(height: 16),
                
                // POP3服务器
                TextFormField(
                  controller: _popServerController,
                  decoration: const InputDecoration(
                    labelText: 'POP3服务器',
                    hintText: 'pop.example.com',
                    prefixIcon: Icon(Icons.dns),
                    border: OutlineInputBorder(),
                  ),
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return '请输入POP3服务器地址';
                    }
                    return null;
                  },
                ),
                const SizedBox(height: 16),
                
                // POP3端口
                TextFormField(
                  controller: _popPortController,
                  decoration: const InputDecoration(
                    labelText: 'POP3端口',
                    hintText: '995',
                    prefixIcon: Icon(Icons.settings_ethernet),
                    border: OutlineInputBorder(),
                  ),
                  keyboardType: TextInputType.number,
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return '请输入POP3端口';
                    }
                    if (int.tryParse(value) == null) {
                      return '请输入有效的端口号';
                    }
                    return null;
                  },
                ),
                const SizedBox(height: 8),
                
                // 安全连接选项
                Row(
                  children: [
                    Checkbox(
                      value: _isSecure,
                      onChanged: (value) {
                        setState(() {
                          _isSecure = value ?? true;
                        });
                      },
                    ),
                    const Text('使用SSL/TLS安全连接'),
                  ],
                ),
                
                // 记住我选项
                Row(
                  children: [
                    Checkbox(
                      value: _rememberMe,
                      onChanged: (value) {
                        setState(() {
                          _rememberMe = value ?? true;
                        });
                      },
                    ),
                    const Text('记住我的登录信息'),
                  ],
                ),
                
                if (_errorMessage != null)
                  Padding(
                    padding: const EdgeInsets.symmetric(vertical: 8.0),
                    child: Text(
                      _errorMessage!,
                      style: const TextStyle(color: Colors.red),
                      textAlign: TextAlign.center,
                    ),
                  ),
                
                const SizedBox(height: 16),
                
                // 登录按钮
                ElevatedButton(
                  onPressed: _isLoading ? null : _login,
                  style: ElevatedButton.styleFrom(
                    padding: const EdgeInsets.symmetric(vertical: 16),
                  ),
                  child: _isLoading
                      ? const CircularProgressIndicator()
                      : const Text('登录', style: TextStyle(fontSize: 16)),
                ),
                
                const SizedBox(height: 16),
                
                // 常见邮箱服务器提示
                const ExpansionTile(
                  title: Text('常见邮箱POP3服务器设置'),
                  children: [
                    ListTile(
                      title: Text('QQ邮箱'),
                      subtitle: Text('服务器: pop.qq.com, 端口: 995, SSL: 是'),
                    ),
                    ListTile(
                      title: Text('163邮箱'),
                      subtitle: Text('服务器: pop.163.com, 端口: 995, SSL: 是'),
                    ),
                    ListTile(
                      title: Text('Gmail'),
                      subtitle: Text('服务器: pop.gmail.com, 端口: 995, SSL: 是'),
                    ),
                    ListTile(
                      title: Text('Outlook/Hotmail'),
                      subtitle: Text('服务器: outlook.office365.com, 端口: 995, SSL: 是'),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}